iT邦幫忙

2022 iThome 鐵人賽

DAY 25
0
Modern Web

clojure 刷刷鍋系列 第 25

Clojure 肉片 -第 25 塊

  • 分享至 

  • xImage
  •  

【今日湯底】

The goal of this exercise is to convert a string to a new string where each character in the new string is "(" if that character appears only once in the original string, or ")" if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.

Examples
"din" => "((("
"recede" => "()()()"
"Success" => ")())())"
"(( @" => "))(("
Notes
Assertion messages may be unclear about what they display in some languages. If you read "...It Should encode XXX", the "XXX" is the expected result, not the input!

(必須通過以下測試)

(ns kata.test
  (:require [clojure.test :refer :all]))

(defn dotest [text expected]
  (is (= (kata.core/encode-dups text) expected)))

(deftest sample
  (testing "basic"
    (dotest "din" "(((")
    (dotest "recede" "()()()")
    (dotest "(( @" "))((")
    (dotest "ABC" "(((")
    (dotest "AaBbC" "))))(")
  )
  (testing "ignore-case" (dotest "Success" ")())())"))
)

【我的答案】

(ns kata.core)

(defn encode-dups [text] 
    (let [lowered-text (clojure.string/lower-case text)
          freqen       (frequencies lowered-text)]
      (->> lowered-text
        (map #(if (= 1 (freqen %)) "(" ")"))
        (clojure.string/join "")))
  )

有找到 frequencies 但卡在怎麼把 map value 為 1 -> "(" 非 1 -> ")" 然後再用 replace 去處理,卡太久就先看答案學習了XD

後來再試著寫,目前還是 not all pass QQ

(ns kata.core)

(defn encode-dups [text]
  (let [lowered (clojure.string/lower-case text)]
    (clojure.string/replace lowered #"\S" (reduce merge (map (fn [[k v]] (if (= v 1) {(str k) "("} {(str k) ")"})) (frequencies lowered)))))
  )

【其他人的答案】

(ns kata.core
   (:require [clojure.string :as str]))

(defn encode-dups [text] 
  (let [lowered (str/lower-case text)
        number-of-times (frequencies lowered)]
    (->> lowered
         (map #(if (= 1 (number-of-times %1)) "(" ")"))
         (str/join))))
(ns kata.core)

(defn encode-dups [text] 
   (let [lower-text (clojure.string/lower-case text)
         char-map   (->> lower-text
                      frequencies 
                      (map (fn [[k v]] (if (= v 1) {k "("} {k ")"})))
                      (reduce merge {}))]
     (->> lower-text (map char-map) clojure.string/join)))

上一篇
Clojure 肉片 -第 24 塊
下一篇
Clojure 肉片 -第 26 塊
系列文
clojure 刷刷鍋30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言